# Copyright (c) 2008 Alvin Wang http://cloudwizard.com/
# License New BSD
# See README for additional information

"""Amazon Web Services Cloud Support

"""

from cloudwizard.queue import QueueService
from cloudwizard.queue import QueueDevice
from boto.sqs.connection import SQSConnection
from cloudwizard.config import Config

class Sqs(QueueService):  # encapsulate connection
    """QueueService API
    AWS API
    """

    def __init__(self, auth=None, username='default', **args):
        if auth:
            self.cloud_auth=auth
        else:
            self.cloud_auth = Config( cloud_abbrev = 'aws', config_name=username)
        self.cloud_obj = SQSConnection( self.cloud_auth.data['aws_access_id'], \
            self.cloud_auth.data['aws_secret_key'])
            
    def create(self, queue_name=None):
        """create a queue"""
        if queue_name == None:
            print "Error: must have a queuename"
        else:
            return self.cloud_obj.create_queue(queue_name)

    def find(self, queue_name=None):
        """get a queue device"""
        #'ami-b111f4d8'
        queues = self.olist()
        for q in queues:
            if q.id == queue_name:
                return q
        return None
        
    def delete(self, queue_name=None):
        """delete a queue"""
        #'ami-b111f4d8'
        device = Queue(queue_name=queue_name)
        return device.delete()

    def olist(self):
        return self.cloud_obj.get_all_queues()

    def plist(self, **args):
        result = self.olist()
        for q in result:
            print q.id

class Queue(QueueDevice):  # encapsulate connection
    """QueueService API
    AWS API
    """
    cloud_device = None

    def __init__(self, auth=None, queue_name='default', username='default',
            cloud_obj=None):
        
        if auth:
            self.cloud_auth=auth
        else:
            self.cloud_auth = Config( cloud_abbrev = 'aws', config_name=username)
        self.cloud_obj = SQSConnection( self.cloud_auth.data['aws_access_id'], \
            self.cloud_auth.data['aws_secret_key'])
        self.cloud_device = self.cloud_obj.get_queue(queue_name)
        if self.cloud_device == None:
            print "Error: ", queue_name, " Not found"
        
    def delete(self, queue_name=None):
        """delete a queue"""
        #'ami-b111f4d8'
        self.cloud_obj.delete_queue(self.cloud_device)
        # return Ec2(reservation=aws_reservation)

